"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 向表中导入存有100万行数据的文件
Create At   : 2023/06/02
Owner       : n@ningyali
Description :
        1.建表
        2.向表中导入100万行数据
Expect      :
        1.创建成功
        2.导入数据成功
History     :
    modified at 2020/09/13 by @ningyali:修改70行，适配不同操作系统
"""
import csv
import os
import random
import string
import subprocess
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class LoadData0088(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.case_lable = 'load_data_0088'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.local_path = os.path.join(os.getcwd(), f'{self.case_lable}.csv')
        self.remote_path = os.path.join('/home', self.pri_user.ssh_user,
                                        f'{self.case_lable}.csv')
        self.count = 1000000
        self.cols = 'id int,name text,sex char(10)'

        text1 = '-----step1:创建数据文件；expect:创建成功-----'
        self.log.info(text1)
        rows = list()
        for i in range(self.count):
            name = f'{random.choice(string.ascii_letters) * 3}_' \
                f'{random.randint(1, self.count+1)}'
            sex = random.choice(['男', '女'])
            rows.append([f'#{i}', name, f'{sex};'])
        with open(self.local_path, 'w+', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerows(rows)

        scp_suffix = f'{self.pri_user.ssh_user}@{self.pri_user.ssh_host}:' \
            f'{self.remote_path}'
        cur_ip = subprocess.getoutput("hostname -i|awk '{print $1}'")
        if cur_ip == self.pri_user.ssh_host:
            cmd = f"\\cp -r {self.local_path} {self.remote_path}"
        else:
            cmd = f'''expect <<-EOF
                set timeout 300
                spawn scp {self.local_path} {scp_suffix}
                expect {{
                    "*yes/no*" {{ send "yes\\n"; exp_continue }}
                    "*assword:*" {{ send "{self.pri_user.ssh_password}\\n"; \
                    exp_continue }}
                    eof
                }}\n'''+'EOF'
        self.log.info(cmd)
        res = subprocess.getoutput(cmd)
        self.log.info(res)

        text2 = '-----创建兼容B库；expect:创建成功-----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '-----step1：创建表；expect：建表成功-----'
        self.log.info(text)
        res = self.load_data.create_table(self.pri_sh, self.db_name,
                                          self.t_name, self.cols)
        self.assertTrue(res, '执行失败:' + text)

        text = '--------step2：向表中导入数据；expect：成功--------'
        self.log.info(text)
        sql = f"load data infile '{self.remote_path}' " \
            f"ignore into table {self.t_name} character set 'utf8' " \
            f"fields terminated by ',' enclosed by '''' " \
            f"lines starting by '#' terminated by ';';" \
            f"select count(*) from {self.t_name};"
        res1 = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        rows, _ = self.common.parse_sql_query_res(res1)
        self.assertIn(f'COPY {self.count}', res1, '执行失败' + text)
        self.assertCountEqual(rows, [[f'{self.count}']], '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        res1 = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                        self.db_name,
                                        self.remote_path)

        res2 = subprocess.getoutput(f'rm -rf {self.local_path}')
        self.log.info(res2)
        self.assertTrue(res1, '执行失败:清理环境')
        self.assertEqual(len(res2.strip()), 0)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
